package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserLoginService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserLoginServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserLoginService {
    @Override
    public ResponseResult login(AdLoginDto adLoginDto) {
        if(!StringUtils.isEmpty(adLoginDto.getName()) && !StringUtils.isEmpty(adLoginDto.getName())){
            //查询：根据名字
            AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adLoginDto.getName()));
            //判断用户是否存在
            if(adUser == null){
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //校验密码
            String srcPassword = DigestUtils.md5DigestAsHex((adLoginDto.getPassword() + adUser.getSalt()).getBytes());
            if(!srcPassword.equals(adUser.getPassword())){
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //封装返回参数
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        } else {
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

    }
}
